package day0303;

import java.util.Arrays;

/**
 * 数组实现双端队列：
 *   1. 插入元素  add  头、尾 addFirst  addLast  / offerXXX
 *   2. 删除元素     poolFirst  poolLast
 *   3. 获取元素     peekFirst   peekLast
 *   4. 大小        size
 *
 */
public class MyDeque {

    private Object[] objs;

    private int size;

    private static final int DEFAULT_LENGTH = 10;

    public MyDeque() {
        objs = new Object[DEFAULT_LENGTH];
    }

    public MyDeque(int length){
        if (length < 0){
            throw new IllegalArgumentException("length 不能小于0 ： " + length);
        }
        objs = new Object[length];
    }

    public void add(Object element) {
        addLast(element);
    }

    public void addFirst(Object element) {
        capacity(size + 1);
        System.arraycopy(objs, 0, objs, 1, size);
        objs[0] = element;
        size ++;
    }

    public void addLast(Object element) {
        capacity(size + 1);

        objs[size ++] = element;
    }

    private void capacity(int length) {
        if (length == objs.length) {
            objs = Arrays.copyOf(objs, objs.length + 10);
        }
    }

    public int size() {
        return this.size;
    }

    public Object peekFirst() {
        return objs[0];
    }

    public Object peekLast() {
        return objs[size - 1];
    }

    public Object poolFirst(){
        check();
        Object obj = objs[0];
        System.arraycopy(objs, 1, objs, 0, size - 1);
        objs[-- size] = null; // GC
        return obj;
    }


    public Object poolLast() {
        check();
        // 队列尾元素取出来
        Object obj = objs[size - 1];
        // 元素删除
        objs[-- size] = null; // GC
        return obj;
    }

    private void check(){
        if (size == 0) {
            throw new RuntimeException("队列中没有元素");
        }
    }
}
